<template>
	<view class="login-page">
		<view class="hero-section">
			<image class="logo" src="/static/logo.png" mode="aspectFit" />
			<view class="title">创数团队</view>
			<view class="subtitle">欢迎加入团队小程序</view>
		</view>

		<view class="content-card">
			<view class="card-title">微信一键登录</view>
			<view class="card-desc">用于同步团队信息、签到和动态</view>

			<button
				class="login-button"
				type="primary"
				:loading="isLogging"
				:disabled="isLogging"
				@click="handleLogin"
			>
				{{ isLogging ? '登录中...' : '立即登录' }}
			</button>

			<view class="agreement">
				登录即代表同意
				<text class="link" @click="openDocs('agreement')">用户协议</text>
				和
				<text class="link" @click="openDocs('privacy')">隐私政策</text>
			</view>
		</view>
	</view>
</template>

<script>
import { wechatLogin } from '@/services/user';
import { saveAuth } from '@/utils/auth';

export default {
	data() {
		return {
			isLogging: false,
			lastLoginCode: '',
			lastCodeGeneratedAt: 0
		};
	},
	methods: {
		async handleLogin() {
			if (this.isLogging) return;
			this.isLogging = true;
			console.log('[login] start login flow');
			try {
				const userProfile = await this.getUserProfile();
				console.log('[login] got user profile', userProfile?.nickName);

				const code = await this.getLoginCode();
				this.lastLoginCode = code;
				this.lastCodeGeneratedAt = Date.now();
				console.log(
					'[login] got wx.login code',
					code,
					'generated at',
					new Date(this.lastCodeGeneratedAt).toISOString()
				);

				const requestStart = Date.now();
				const userData = await wechatLogin({
					code,
					nickname: userProfile.nickName,
					avatarUrl: userProfile.avatarUrl
				});
				console.log(
					'[login] backend login success, elapsed',
					Date.now() - requestStart,
					'ms'
				);

				// 兼容后端直接返回用户对象或者 { user, token }
				const userInfo = userData?.user || userData;
				const token = userData?.token;
				saveAuth(userInfo, token);

				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});

				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}, 500);
			} catch (error) {
				console.error('微信登录失败', error);
				uni.showToast({
					title: error?.message || '登录失败，请重试',
					icon: 'none'
				});
			} finally {
				this.isLogging = false;
			}
		},
		getUserProfile() {
			return new Promise((resolve, reject) => {
				uni.getUserProfile({
					desc: '用于完善团队资料',
					lang: 'zh_CN',
					success: (res) => resolve(res.userInfo),
					fail: (err) => reject(err)
				});
			});
		},
		getLoginCode() {
			return new Promise((resolve, reject) => {
				console.log('[login] calling wx.login ...');
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: (res) => {
						if (res.code) {
							console.log('[login] wx.login success, code=', res.code);
							resolve(res.code);
						} else {
							reject(new Error('未获取到登录凭证'));
						}
					},
					fail: (err) => reject(err)
				});
			});
		},
		openDocs(type) {
			const title = type === 'privacy' ? '隐私政策' : '用户协议';
			uni.showToast({
				title: `${title}即将上线`,
				icon: 'none'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.login-page {
	min-height: 100vh;
	background: linear-gradient(180deg, #eef2ff 0%, #ffffff 50%);
	padding: 120rpx 48rpx 60rpx;
	box-sizing: border-box;
}

.hero-section {
	text-align: center;
	margin-bottom: 60rpx;
}

.logo {
	width: 160rpx;
	height: 160rpx;
	margin-bottom: 32rpx;
}

.title {
	font-size: 48rpx;
	font-weight: 600;
	color: #111827;
	margin-bottom: 12rpx;
}

.subtitle {
	font-size: 28rpx;
	color: #6b7280;
}

.content-card {
	background: #ffffff;
	border-radius: 32rpx;
	padding: 48rpx;
	box-shadow: 0 20rpx 40rpx rgba(99, 102, 241, 0.1);
}

.card-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #111827;
	margin-bottom: 12rpx;
}

.card-desc {
	font-size: 26rpx;
	color: #6b7280;
	margin-bottom: 48rpx;
}

.login-button {
	background: linear-gradient(135deg, #6366f1, #8b5cf6);
	border: none;
	border-radius: 999rpx;
	height: 96rpx;
	line-height: 96rpx;
	font-size: 32rpx;
	font-weight: 600;
}

.agreement {
	margin-top: 32rpx;
	font-size: 24rpx;
	color: #9ca3af;
	text-align: center;
}

.link {
	color: #6366f1;
	margin: 0 8rpx;
}
</style>

